﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.Bll;

public partial class Templates_Profile_Edit : LoggedInPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        valEmailFormat.ValidationExpression = Acms.Bll.UserHelper.EmailValidationExpression;
        valPasswordFormat.ValidationExpression = Acms.Bll.UserHelper.PasswordValidationExpression;
        valPasswordFormat.ErrorMessage = Acms.Bll.UserHelper.PasswordFormatErrorMessage;
        btnSubmit.Click += new EventHandler(btnSubmit_Click);
        btnPassword.Click += new EventHandler(btnPassword_Click);
        btnEmail.Click += new EventHandler(btnEmail_Click);
        btnRemove.Click += new EventHandler(btnRemove_Click);
        if (!IsPostBack)
        {
            if (AcmsContext.SiteId > 0)
            {
                CarbonExchange.Bll.CountryFactory factory = new CarbonExchange.Bll.CountryFactory();
                ddlCountry.DataValueField = "Id";
                ddlCountry.DataTextField = "Name";
                ddlCountry.DataSource = factory.GetAllBySiteId(AcmsContext.SiteId);
                ddlCountry.DataBind();
            }
            DataBind();
        }
    }

    void btnRemove_Click(object sender, EventArgs e)
    {
        if (IsValid && User.Identity.User.GetThumbnailId().HasValue)
        {
            var user = User.Identity.User;
            var oldFile = Acms.Bll.File.GetById(user.GetThumbnailId().Value);
            if (oldFile != null)
            {
                user.BeginTransaction();
                oldFile.UseTransaction(user.TransactionKey);
                oldFile.Delete();
                user.SetThumbnailId(null);
                try
                {
                    user.Update();
                }
                catch
                {
                    user.RollbackTransaction();
                    throw;
                }
                user.CommitTransaction();
                imgThumb.FileId = null;
                imgNoThumb.Visible = true;
                liRemoveThumb.Visible = false;
            }

        }
    }

    void btnEmail_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            CarbonExchange.Bll.EmailRestrictionFactory factory = new CarbonExchange.Bll.EmailRestrictionFactory();
            var valid = factory.ValidateEmail(txtEmail.Text, factory.GetAllBySiteId(AcmsContext.SiteId));
            if (!valid)
            {
                pnlNonApprovedEmail.Visible = true;
                return;
            }

            try
            {
                var result = Acms.Bll.EmailActivationCode.CreateInstance(User.Identity.User, txtEmail.Text, AcmsContext.SiteId);
                result.Update();
                result.Send(Server.MapPath("~/Sites/Man/Emails/AuthenticateEmail.xml"), AcmsContext.SiteRoot, AcmsContext.GetUrl("~/Profile/ActivateEmail.aspx"));
            }
            catch(Acms.Exceptions.DuplicateEmailException)
            {
                pnlDuplicateEmailError.Visible = true;
                return;
            }

            pnlEmailMessage.Visible = true;
            ulEmailMessage.InnerHtml = string.Format("<li>You email has been changed but needs to be authenticated. Check your '{0}' email inbox.</li>", txtEmail.Text);
        }
    }

    void btnPassword_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            var result = User.Identity.User.SetPassword(txtOldPassword.Text, txtPassword.Text);
            if (result)
            {
                User.Identity.User.Update();
                ulPasswordMessage.InnerHtml = "<li>Password Set Succsefully</li>";
                pnlPasswordMessage.Visible = true;
            }
            else
            {
                ulPasswordError.InnerHtml = "<li>Old Password is not a match. Please check and try again.</li>";
                pnlPasswordError.Visible = true;
            }
        }
    }

    public override void DataBind()
    {
        var user = User.Identity.User;
        if (user != null)
        {
            lblCurrentEmail.Text = user.EmailAddress;
            txtFirstName.Text = user.FirstName;
            txtLastName.Text = user.LastName;
            txtDepartment.Text = user.GetDepartment();
            ddlCountry.SelectedValue = user.GetCountryId().ToString();
            ddlState.SelectedValue = user.GetState();
            cboAnon.Checked = user.GetAnon();
            txtComment.Text = user.GetComment();
            imgThumb.FileId = user.GetThumbnailId();
            imgNoThumb.Visible = !imgThumb.FileId.HasValue;
            liRemoveThumb.Visible = imgThumb.FileId.HasValue;
        }
        base.DataBind();
    }

    public override void Validate(string validationGroup)
    {
        var tmpName = ddlCountry.SelectedItem.Text.ToLower().Replace(" ", "");
        valStateReq.Enabled = (tmpName == "usa" || tmpName == "unitedstatesofamerica" || tmpName == "unitedstates");
        base.Validate(validationGroup);
    }

    void btnSubmit_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            var user = User.Identity.User;
            user.SetAnon(cboAnon.Checked);
            user.SetComment(txtComment.Text);
            user.SetCountryId(int.Parse(ddlCountry.SelectedValue));
            var tmpName = ddlCountry.SelectedItem.Text.ToLower().Replace(" ", "");
            if (tmpName == "usa" || tmpName == "unitedstatesofamerica" || tmpName == "unitedstates")
            {
                user.SetState(ddlState.SelectedValue);
            }
            else
            {
                user.SetState(null);
            }
            user.FirstName = txtFirstName.Text;
            user.LastName = txtLastName.Text;
            user.SetDepartment(txtDepartment.Text);

            if (upload.HasFile)
            {
                user.BeginTransaction();
                if (user.GetThumbnailId().HasValue)
                {
                    var oldFile = Acms.Bll.File.GetById(user.GetThumbnailId().Value);
                    if (oldFile != null)
                    {
                        oldFile.UseTransaction(user.TransactionKey);
                        oldFile.Delete();
                    }
                }
                var newFile = Acms.Bll.File.CreateInstance(File.FileTypes.Image, upload.PostedFile, upload.FileBytes, 800, 800);
                newFile.UseTransaction(user.TransactionKey);
                newFile.Update();

                user.SetThumbnailId(newFile.Id);
            }

            try
            {
                user.Update();
            }
            catch
            {
                if(user.TransactionKey != Guid.Empty)
                    user.RollbackTransaction();
                throw;
            }

            if (user.TransactionKey != Guid.Empty)
                user.CommitTransaction();

            imgThumb.FileId = user.GetThumbnailId();
            imgNoThumb.Visible = !imgThumb.FileId.HasValue;
            liRemoveThumb.Visible = imgThumb.FileId.HasValue;
        }
    }
}
